<script setup>
import { onMounted, reactive, ref, inject, computed } from 'vue'
import { DlMessageBox } from '../util/messagebox.js';
import { IconTopCircle } from '../icon/index.js'
import DlLoading from '../components/DlLoading.vue'

//引入 api
import { findUserOrderFun, userCancelOrderFun, userConfirmReceiptFun, userRemoveOrderFun } from '../api/order.js'

const statusArr = ref([
    {name: '全部', value: 0},
    {name: '待付款', value: 1},//1已下单
    {name: '待发货', value: 2},//2已付款
    {name: '待收货', value: 3},//3已发货
    {name: '待评价', value: 4},//4已收货
    {name: '已完成', value: 5},//5已评价
    //6已删除,7已取消
]);
const statusNameArr = ['未知', '待付款', '待发货', '待收货', '待评价', '已完成', '已删除', '已取消'];
//顶部菜单相关
const barLine = reactive({left: 0, width: 0, height: 0});
function doChangeStatusMenu(ele, st) {
    if(loading.value) {
        DlMessageBox.warning('数据加载中,\n请稍后再试!');
        return;
    }
    barLine.left = ele.offsetLeft;
    barLine.width = ele.offsetWidth;
    barLine.height = ele.offsetHeight;
    // console.log(ele, ele.offsetLeft, ele.offsetWidth);
    // 获取菜单对应的订单
    currentStatus.value = st.value;
    currentPageNum.value = 1;
    //清空其他状态的订单
    orderArr.value = [];
    //重新加载
    doLoadData();
}
const statusBarListRef = ref(null);
function initBarLine() {//初始化顶部菜单
    if(statusBarListRef.value) {
        let arr = statusBarListRef.value.children;
        if(arr[0]) {
            arr[0].click();
        }
    }
}

const currentStatus = ref(0);//当前选中的菜单的数值
const orderArr = ref([]);//订单数据
const currentPageNum = ref(1);
const pageSize = 5;
const pages = ref(0);//总页数
const loading = ref(false);//加载中
const noMoreData = ref(false);//是否已没有更多数据了
function doLoadData() {
    //登录后才加载数据
    if(!isLogin.value) {
        return;
    }
    noMoreData.value = false;
    loading.value = true;//加载中...
    //根据订单的状态获取订单数据
    let params = {
        status: currentStatus.value,
        pageNum: currentPageNum.value,
        pageSize: pageSize,
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
            let key = orderArr.value.length;
            //测试数据
            let status = params.status == 0 ? 5:params.status;
            dataArr.push({
                id: key+1, no: 'xiaoqiao20240712141733', totalPrice: '56.59', totalNum: 2, status: status, details: [
                    {id: 11, productId:1, title:'农村散养土鸡蛋', image:'./product/product7.jpg', price:21.9, num:1, type:'1斤'},
                    {id: 12,productId:2, title:'宁夏精品枸杞', image:'./product/product5.jpg', price:34.69, num:1, type:'1罐'},
                ], name:'汤姆', phone:'12345678901', addr: '江苏南京江北新区XXX社区XX路NN号SSSS',
            });
            dataArr.push({
                id: key+2, no: 'xiaoqiao20240606123245', totalPrice: '164.48', totalNum: 12, status: status, details: [
                    {id: 11, productId:1, title:'休闲男士衬衫百搭', image:'./product/product1.jpg', price:39.89, num:1, type:'XL'},
                    {id: 11, productId:1, title:'抽纸结实耐用', image:'./product/product6.jpg', price:8.99, num:10, type:'L'},
                    {id: 12,productId:2, title:'宁夏精品枸杞', image:'./product/product5.jpg', price:34.69, num:1, type:'1罐'},
                ], name:'汤姆', phone:'12345678901', addr: '江苏南京江北新区XXX社区XX路NN号SSSS',
            });
    
            key = orderArr.value.length + 2;
            let i=1;
            for(; i< 4; i++) {
                dataArr.push({
                    id: i+key, no: 'xxxxxxxxxxxxxxxxxxxxxx', totalPrice: '229.95', totalNum: 5, status: status, details: [
                        {id: i+key+''+1, productId:1, title:'测试商品11', image:'./product.jpg', price:99.99, num:2, type:'xxx'},
                        {id: i+key+''+2,productId:2, title:'测试商品22', image:'./product.jpg', price:9.99, num:3, type:'sss'},
                    ], name:'汤姆', phone:'12345678901', addr: '江苏南京江北新区XXX社区XX路NN号SSSS',
                });
            }
            // console.log('dataArr:', dataArr);
            //处理状态显示
            dataArr.forEach(o => {
                o.statusName = statusNameArr[o.status];
                orderArr.value.push(o);
            });
            pages.value = 3;//获取总页数
            loading.value = false;//加载结束
            noMoreData.value = currentPageNum.value >= pages.value;
        }, 1000);
    } else {
        //请求api
        findUserOrderFun(params.status, params.pageNum, params.pageSize).then((result)=>{
            console.log('findUserOrderFun result:', result);
            if (result.code == 200) {
                //DlMessageBox.success(result.msg);
                let data = result.data;
                //处理状态显示
                data.list.forEach(o => {
                    o.statusName = statusNameArr[o.status];
                    if (o.statusName == undefined) {
                        o.statusName = '未知';
                    }
                    orderArr.value.push(o);
                });
                pages.value = data.pages;//获取总页数
                noMoreData.value = currentPageNum.value >= pages.value;
            } else {
                DlMessageBox.error(result.msg);
            }
            loading.value = false;
        });
    }
}

// 改变订单状态
function doCancelOrder(order) {
    //取消订单
    let params = {
        id: order.id
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        order.status = 7;
        //操作成功后执行
        DlMessageBox.success('成功取消订单', 3000);
        currentPageNum.value = 1;
        //清空其他状态的订单
        orderArr.value = [];
        //重新加载
        doLoadData();
    } else {
        //请求api
        userCancelOrderFun(params.id).then((result)=>{
            console.log('userCancelOrderFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);

                currentPageNum.value = 1;
                //清空其他状态的订单
                orderArr.value = [];
                //重新加载
                doLoadData();
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}
function doConfirmOk(order) {
    //确认收货
    let params = {
        id: order.id
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        order.status = 4;
        //操作成功后执行
        DlMessageBox.success('确认收货成功');
        currentPageNum.value = 1;
        //清空其他状态的订单
        orderArr.value = [];
        //重新加载
        doLoadData();
    } else {
        //请求api
        userConfirmReceiptFun(params.id).then((result)=>{
            console.log('userConfirmReceiptFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //操作成功后执行
                currentPageNum.value = 1;
                //清空其他状态的订单
                orderArr.value = [];
                //重新加载
                doLoadData();
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}
function doRemoveOrder(order) {
    //删除已完成的订单
    let params = {
        id: order.id
    };
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        order.status = 6;
        //操作成功后执行
        DlMessageBox.success('成功删除订单');
        currentPageNum.value = 1;
        //清空其他状态的订单
        orderArr.value = [];
        //重新加载
        doLoadData();
    } else {
        //请求api
        userRemoveOrderFun(params.id).then((result)=>{
            console.log('userRemoveOrderFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //操作成功后执行
                currentPageNum.value = 1;
                //清空其他状态的订单
                orderArr.value = [];
                //重新加载
                doLoadData();
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

//去付款
function goToPay(order) {
    //console.log('order:', order);
    //去付款页面
    localStorage.setItem('orderId', order.id);
    menuCore.push('/pay');
}

//催发货
function doSendMsg(order) {
    DlMessageBox.warning('功能开发中...');
}
//去评论
function goToComment(order) {
    localStorage.setItem('orderId', order.id);
    menuCore.push('/comment');
}
//查看物流信息
function goToLogistics(order) {
    DlMessageBox.warning('功能开发中...');
}

//滚动事件
function doChangeScroll(e) {
    // console.log('doChangeScroll:', e);
    let t = e.target;
    // t.offsetHeight;//窗口高度
    // t.scrollTop;//滚动的高度
    // t.scrollHeight;//可滚动高度

    //回到顶部按钮处理, 显示与隐藏
    showTopBtn.value = t.scrollTop > showHideTop;

    let offsetNum = 10;//误差值
    let height = t.scrollHeight - t.offsetHeight - t.scrollTop - offsetNum;
    // 到底加载更多
    if(height <= 0) {
        //console.log('滚动到底部了...');
        //如果还有数据,则加载;如果正在加载中,则不再执行
        if(!loading.value && currentPageNum.value < pages.value) {
            currentPageNum.value++;
            doLoadData();
        }
    }
}
const showTopBtn = ref(false);
const showHideTop = 300;//隐藏和显示的scrollTop
const topBtnStyle = computed(()=>{
    let bottom = 40;
    let right = -1.8;
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        bottom+=h;
    }
    if(showTopBtn.value) {
        right = 0.6;
    }
    return {bottom: bottom+'px', right: right+'rem'};
});
//回到顶部
function doGoTop() {
    if(viewRef.value) {
        viewRef.value.scrollTo({top: 0, behavior: 'smooth'});
    }
}

//主页底部菜单对象
const menuCore = inject('menuCore');
//底部主菜单
const homeMenuBar = inject('homeMenuBar');
const viewRef = ref(null);
const viewHeight = computed(()=>{//计算展示区域高度
    let vh = 770;
    if(viewRef.value) {
        let p = viewRef.value.parentElement;
        vh = p.offsetHeight;
    }
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        vh -= h;
    }
    return vh;
});

//登录用户缓存
const loginUser = inject('loginUser');
//是否登录
const isLogin = ref(false);
function doCheckLogin() {
    if(!loginUser.value || !loginUser.value.token) {
        DlMessageBox.error('您还未登录,\n请先登录!');
        menuCore.push('/login');
        return;
    }
    isLogin.value = true;
}

onMounted(()=>{
    doCheckLogin();
    initBarLine();
});


</script>
<template>
    <div class="view-dl" ref="viewRef" :style="'height:'+viewHeight+'px'" @scroll="doChangeScroll">
        <div class="title-dl">我的订单</div>
        <div class="status-bar-list-dl" ref="statusBarListRef">
            <div class="bar-item-dl" :class="(st.value == currentStatus ? 'bar-active':'')"
             v-for="st in statusArr" :key="st.name" @click="doChangeStatusMenu($event.target, st)" >{{st.name}}</div>
            <div class="bar-line-dl" 
            :style="{left: barLine.left+'px', width: barLine.width+'px', height: barLine.height+'px'}"></div>
        </div>
        <div class="order-list-dl">
            <div class="order-dl" v-for="o in orderArr" :key="o.id">
                <div class="order-head-dl">
                    <div class="order-no-dl">订单编号：{{o.no}}</div>
                    <div class="order-status-dl">{{o.statusName}}</div>
                </div>
                <div class="order-body-dl">
                    <div class="order-detail-dl" v-for="d in o.details" :key="d.id" >
                        <div class="img-dl"><img :src="d.image" alt="no image"></div>
                        <div class="detail-txt-dl">
                            <div class="detail-title-dl">{{d.title}}</div>
                            <div class="detail-type-dl">规格: {{d.type}}</div>
                        </div>
                        <div class="right-dl">
                            <div class="price-dl">￥{{d.price}}</div>
                            <div class="num-dl">x {{d.num}}</div>
                        </div>
                    </div>
                </div>
                <div class="order-foot-dl">
                    <div class="foot-tip-dl">
                        <span>共计</span>
                        <span class="tip-dl">{{o.totalNum}}</span>
                        <span>件商品, 合计：</span>
                        <span class="tip-dl" >￥{{o.totalPrice}}</span>
                    </div>
                    <div class="foot-act-dl">
                        <div class="btn-dl" v-if="o.status == 1" @click="doCancelOrder(o)">取消订单</div>
                        <div class="btn-dl" v-if="o.status == 1" @click="goToPay(o)">去付款</div>
                        <div class="btn-dl" v-if="o.status == 2" @click="doSendMsg(o)">催发货</div>
                        <div class="btn-dl" v-if="o.status == 3" @click="doConfirmOk(o)">确认收货</div>
                        <div class="btn-dl" v-if="o.status == 4" @click="goToComment(o)">去评价</div>
                        <div class="btn-dl" v-if="o.status == 5" @click="doRemoveOrder(o)">删除订单</div>
                        <div class="btn-dl" v-if="o.status >= 3 && o.status <= 5 " @click="goToLogistics(o)">查看物流</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="foot-dl" :style="'height: '+ (loading ? '2rem':'auto')">
            <!-- 加载中动画... -->
            <DlLoading style="font-size: 1rem" v-show="loading" />
            <!-- 其他提示 -->
            <div class="no-more-data-dl" v-show="!loading && noMoreData" >暂无更多数据</div>
        </div>
        <div class="top-btn-dl" :style="topBtnStyle">
            <IconTopCircle class="icon-dl" @click="doGoTop" />
        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    overflow: hidden auto;
}
.title-dl {
    font-size: 0.6rem;
    height: 1rem;
    line-height: 1rem;
    text-align: center;
    padding: 0.2rem;
    background-color: #fff;
    color: #333;
}

.status-bar-list-dl {
    padding: 0.2rem;
    margin: 0.1rem 0;
    background-color: #fff;
    display: flex;
    justify-content: space-evenly;
    position: sticky;
    top: 0;
    color: #333;
}
.bar-item-dl {
    cursor: pointer;
    padding: 0.1rem 0.2rem;
    transition: color 0.8s ease-in-out;
    position: relative;
    z-index: 2;
}
.bar-active {
    color: #fff;
}
.status-bar-list-dl .bar-line-dl {
    position: absolute;
    background-color: #009dff;
    border-radius: 0.07rem;
    transition: all 0.5s ease-in-out;
    z-index: 1;
}

.order-list-dl {
    margin: 0.2rem 0;
}
.order-dl {
    padding: 0.2rem;
    border-bottom: 1px solid #ccc;
    margin: 0.2rem 0;
    background-color: #fff;
    border-radius: 0.1rem;
    color: #333;
}
.order-dl:last-child {
    border-bottom: none;
}
.order-head-dl {
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #ccc;
}
.order-no-dl {
    font-size: 0.36rem;
    color: #999;
}
.order-status-dl {
    font-weight: bold;
    color: #900000;
    flex-shrink: 0;
}
.order-body-dl {
    margin: 0.1rem 0;
}
.order-detail-dl {
    margin-bottom: 0.1rem;
    display: flex;
    border-bottom: 1px solid #ccc;
}
.order-detail-dl .img-dl {
    width: 2rem;
    height: 2rem;
    flex-shrink: 0;
}
.img-dl img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    font-size: 0.4rem;
    display: block;
}

.detail-txt-dl {
    flex: 1 1 auto;
    padding: 0 0.2rem;
    overflow: hidden;
}
.detail-txt-dl .detail-title-dl {
    font-weight: bold;
    overflow: hidden;
    text-overflow: ellipsis;
    /* white-space: nowrap; */
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
}
.detail-txt-dl .detail-type-dl {
    color: #999;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.order-detail-dl .right-dl {
    text-align: right;
    flex-shrink: 0;
}
.right-dl .price-dl {
    color: #d00000;
    margin-bottom: 0.3rem;
}
.right-dl .num-dl{
    color: #999;
}

.order-foot-dl {
    text-align: right;
    font-size: 0.3rem;
}
.tip-dl {
    color: #000;
    font-weight: bold;
    font-size: 0.4rem;
}
.foot-act-dl {
    margin-top: 0.1rem;
}

.btn-dl {
    display: inline-block;
    color: #fff;
    font-weight: bold;
    padding: 0.1rem 0.4rem;
    margin: 0.1rem;
    border-radius: 0.8rem;
    background-color: #900000;
    cursor: pointer;
}
.btn-dl:hover {
    background-color: #d00000;
}
.foot-dl {
    text-align: center;
    color: #aaa;
}
.foot-dl .icon-dl {
    width: 1.4rem;
    height: 1.4rem;
}

.no-more-data-dl {
    font-size: 0.52rem;
    padding: 0.1rem 0 0.3rem;
}

.top-btn-dl {
    position: fixed;
    transition: all 0.2s linear;
}
.top-btn-dl .icon-dl {
    width: 1.6rem;
    height: 1.6rem;
    color: #fff;
    background-color: #999c;
    border-radius: 50%;
    cursor: pointer;
}
</style>